package com.course.servlet;

import com.course.entity.Course;
import com.course.entity.Teacher;
import com.course.service.CourseService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/laoshi_publish_course")
public class LaoshiPublishCourseServlet extends HttpServlet {
    private final CourseService courseService = new CourseService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        HttpSession session = request.getSession(false); // Do not create a new session if one doesn't exist
        System.out.println("LaoshiPublishCourseServlet: Session ID from request: " + (session != null ? session.getId() : "No Session"));

        Teacher teacher = null;
        if (session != null) {
            teacher = (Teacher) session.getAttribute("teacher");
            System.out.println("LaoshiPublishCourseServlet: Teacher object from session is null: " + (teacher == null));
        }

        if (teacher == null) {
            System.out.println("LaoshiPublishCourseServlet: Teacher is null, redirecting to login.");
            response.sendRedirect(request.getContextPath() + "/laoshi_login.jsp");
            return;
        }

        System.out.println("LaoshiPublishCourseServlet: Teacher logged in: " + teacher.getName() + " (ID: " + teacher.getId() + ")");

        String courseName = request.getParameter("courseName");
        String courseDescription = request.getParameter("courseDescription");
        int maxCapacity = Integer.parseInt(request.getParameter("maxCapacity"));

        Course course = new Course();
        course.setCourseName(courseName);
        course.setCourseDescription(courseDescription);
        course.setTeacherId(teacher.getId()); // 设置发布课程的老师ID
        course.setMaxCapacity(maxCapacity);

        boolean success = courseService.addCourse(course);

        if (success) {
            request.setAttribute("successMessage", "课程发布成功！");
        } else {
            request.setAttribute("errorMessage", "课程发布失败，请检查输入或联系管理员。");
        }
        request.getRequestDispatcher("/laoshi_publish_course.jsp").forward(request, response);
    }
} 